package main

import (
	"database/sql"
	"time"
)

func InitDB() {
	var err error
	Db, err = sql.Open("sqlite3", "./diary.db")
	if err != nil {
		panic(err)
	}

	//数据表除了在命令行提前进行创建，还可以在go程序中创建，如下：
	sql_table := `
CREATE TABLE IF NOT EXISTS "diary" (
    "id" INTEGER PRIMARY KEY AUTOINCREMENT,
    "cls" TEXT NOT NULL default ('日志'),
    "title" TEXT NOT NULL,
	"content" TEXT NOT NULL,
    "createdate" TIMESTAMP default (datetime('now', 'localtime'))
);
`
	_, err = Db.Exec(sql_table)
	if err != nil {
		panic(err)
	}
}

type Diary struct {
	Id         int32     `json:"id"`
	Cls        string    `json:"cls"`
	Title      string    `json:"title"`
	Content    string    `json:"content"`
	Createdate time.Time `json:"createdate"`
}

func GetAllDiary() []Diary {
	rows, _ := Db.Query("SELECT * FROM diary")
	var ds = []Diary{}
	for rows.Next() {
		var d = Diary{}
		_ = rows.Scan(&d.Id, &d.Cls, &d.Title, &d.Content, &d.Createdate)
		ds = append(ds, d)
	}
	return ds
}

func PutDiary(d *Diary) (id int64, err error) {
	stmt, err := Db.Prepare("INSERT INTO diary(`cls`, `title`, `content`)  values(?, ?, ?);")
	if err != nil {
		return 0, err
	}
	res, err := stmt.Exec(d.Cls, d.Title, d.Content)
	if err != nil {
		return 0, err
	}
	id, err = res.LastInsertId()
	if err != nil {
		return 0, err
	}
	return
}
